package com.fivefu.core.hik.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.hik.constant.HikRequestTypeEnum;
import com.fivefu.core.hik.dto.request.VehicleLicensePlate;
import com.fivefu.core.hik.dto.request.VehicleOrgIndexCodes;
import com.fivefu.core.hik.dto.response.EncodeVehicleDetail;
import com.fivefu.core.hik.dto.response.EncodeVehicleShapestr;
import com.fivefu.core.hik.dto.response.ResponsePage;
import com.fivefu.core.hik.dto.response.ResponseResult;
import com.fivefu.core.hik.entity.DbHikVehicle;
import com.fivefu.core.hik.services.DbHikRegionsService;
import com.fivefu.core.hik.services.DbHikVehicleService;
import com.fivefu.core.hik.services.HikVehicleService;
import com.fivefu.core.hik.services.HikvisionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HikVehicleServiceImpl implements HikVehicleService {

    @Resource
    private HikvisionService hikvisionService;

    @Resource
    private DbHikRegionsService hikRegionsService;

    @Resource
    private DbHikVehicleService dbHikVehicleService;

    /**
     * 查询车辆信息列表v1
     */
    @Override
    public void searchForVehicleInformation() {
        Integer pageNo = 1;
        Integer pageSize = 1000;
        // 获取未删除区域唯一标识集合
        List<String> areaList = hikRegionsService.queryRegionIDs();
        // 循环查询区域编码车辆关联关系
        for (String area : areaList) {
            List<String> list = new ArrayList<>();
            list.add(area);
            getVehicleInformation(pageNo, pageSize, list);
        }

    }

    /**
     * 查询车辆信息列表v1
     * @param pageNo  当前页码
     * @param pageSize   分页大小
     */
    public void getVehicleInformation(Integer pageNo, Integer pageSize, List<String> list) {
        //查询车辆信息列表v1必需参数
        VehicleOrgIndexCodes vehicleOrgIndexCodes = new VehicleOrgIndexCodes(pageNo, pageSize);
        if (list != null && list.size() > 0){
            JSONObject object = new JSONObject();
            object.put("orgIndexCodes", list);
            vehicleOrgIndexCodes.setExactCondition(object);
        }

        //将请求对象转换为json字符串
        String body = JSON.toJSONString(vehicleOrgIndexCodes);

        //查询类型枚举
        HikRequestTypeEnum typeEnum = HikRequestTypeEnum.VEHICLELISTV1;

        //调用接口
        ResponseResult result = hikvisionService.doPostString(typeEnum.getUrl(), body, null, null, typeEnum.getType());
        ResponsePage resultPage = new ResponsePage();
        if (null != result && "0".equals(result.getCode())) {
            //调用成功
            Object resultData = result.getData();
            if (StrUtils.isNotNull(String.valueOf(resultData))) {
                resultPage = JSON.parseObject(resultData.toString(), ResponsePage.class);
                resultPage.getList().forEach(deviceObj -> {
                    DbHikVehicle vehicle = new DbHikVehicle();
                    EncodeVehicleDetail encodeDeviceSearchResult = JSON.parseObject(JSON.toJSONString(deviceObj), EncodeVehicleDetail.class);
                    // 根据车辆编码，验证数据是否存在
                    DbHikVehicle dbHikVehicle = dbHikVehicleService.getOne(new QueryWrapper<DbHikVehicle>().eq("is_delete", 0).eq("vehicle_index_code", encodeDeviceSearchResult.getVehicleIndexCode()));
                    // 判断根据车辆编码查询这条信息是否存在。如果存在修改，则添加
                    if (dbHikVehicle == null) {
                        vehicle = encodeDeviceSearchResult.replaceDbHikVehicle();
                    } else {
                        vehicle = encodeDeviceSearchResult.replaceDbHikVehicleOne(dbHikVehicle.getId());
                    }
                    //编辑(添加)海康车辆信息
                    dbHikVehicleService.editHikVehicle(vehicle);
                });

                //循环查询分页数据
                if (resultPage.getTotal() > ((pageNo - 1) * pageSize + pageSize)){
                    //调用方法本身，递归完成查询
                    getVehicleInformation(pageNo + 1,pageSize, list);
                }
            }
        }
    }

    /**
     * 根据车牌号码获取车辆信息(含设备)v1
     */
    @Override
    public void vehicleInformation(String vehicleLicensePlate) {
        //根据车牌号码获取车辆信息(含设备)v1必需参数
        VehicleLicensePlate vehicleOrgIndexCodes = new VehicleLicensePlate(vehicleLicensePlate);
        //将请求对象转换为json字符串
        String body = JSON.toJSONString(vehicleOrgIndexCodes);

        //查询类型枚举
        HikRequestTypeEnum typeEnum = HikRequestTypeEnum.VEHICLEDETAIL;

        // 根据车牌号验证这条数据是否已经存在
        Long vehicleId = dbHikVehicleService.getVehicle(vehicleLicensePlate);

        //调用接口
        ResponseResult result = hikvisionService.doPostString(typeEnum.getUrl(), body, null, null, typeEnum.getType());
        if (null != result && "0".equals(result.getCode())) {
            //调用成功
            String resultData = result.getData().toString();
            if (StrUtils.isNotNull(resultData)) {
                // 数据转化对象
                EncodeVehicleDetail encodeDeviceSearchResult = JSON.parseObject(resultData, EncodeVehicleDetail.class);
                DbHikVehicle vehicle = new DbHikVehicle();
                // 判断根据车牌号查询本地是否已经存在数据,如不存在进行添加,则修改
                if (StrUtils.isNull(String.valueOf(vehicleId))) {
                    vehicle = encodeDeviceSearchResult.replaceDbHikVehicle();
                } else {
                    vehicle = encodeDeviceSearchResult.replaceDbHikVehicleOne(vehicleId);
                }
                //编辑(添加)海康车辆信息
                dbHikVehicleService.editHikVehicle(vehicle);
            }
        }
    }

    @Override
    public void vehiclePoint() throws ParseException {
        List<DbHikVehicle> vehicleInformation = dbHikVehicleService.getVehicleInformation();
        for (DbHikVehicle dbHikVehicle : vehicleInformation) {
//            //根据车牌号码获取车辆信息(含设备)v1必需参数
//            VehicleLicensePlate vehicleOrgIndexCodes = new VehicleLicensePlate(dbHikVehicle.getPlateNo());
//            //将请求对象转换为json字符串
//            String body = JSON.toJSONString(vehicleOrgIndexCodes);

            String plateNo = dbHikVehicle.getVehicleIndexCode();

            JSONArray jsonArray = new JSONArray();
            jsonArray.add(plateNo);

            //查询类型枚举
            HikRequestTypeEnum typeEnum = HikRequestTypeEnum.CARPAGELIST;

            //调用接口
            ResponseResult result = hikvisionService.doPostString(typeEnum.getUrl(), jsonArray.toString(), null, null, typeEnum.getType());
            if (null != result && "0".equals(result.getCode())) {
                //调用成功
                String resultData = result.getData().toString();
                String resultDataString = resultData.substring(1, resultData.length() - 1);
                // 数据转化对象
                EncodeVehicleShapestr encodeVehicleShapestr = JSON.parseObject(resultDataString, EncodeVehicleShapestr.class);
                if (encodeVehicleShapestr != null) {
                    // 判断根据车牌号查询本地是否已经存在数据,如不存在返回null,则修改
                    DbHikVehicle vehicle ;
                    vehicle = encodeVehicleShapestr.addShapestrData(dbHikVehicle.getId());
                    //编辑(添加)海康车辆信息
                    dbHikVehicleService.editHikVehicle(vehicle);
                }
            }
        }
    }
}
